<template>
	<div v-cloak class="aui-wrapper aui-page__iframe">
		<div class="aui-content__wrapper">
			<div class="aui-content">
				<el-card shadow="never" class="aui-card--fill">
					<div class="mod-lswms__receiptdetaillist">
						<el-form :inline="true" :model="dataForm" @keyup.enter.native="getDataList()">
							<el-form-item>
								<el-date-picker v-model="dataForm.recipienttime" type="daterange" size="small"
									range-separator="至" start-placeholder="领用日期-开始" end-placeholder="领用日期-结束">
								</el-date-picker>
							</el-form-item>
							<el-form-item>
								<el-input v-model="dataForm.cardid" size="small" placeholder="领用人号" clearable>
								</el-input>
							</el-form-item>
							<el-form-item>
								<el-input v-model="dataForm.recipientid" size="small" placeholder="领用人卡ID" clearable>
								</el-input>
							</el-form-item>
							<el-form-item>
								<el-input v-model="dataForm.recipient" size="small" placeholder="领用人" clearable>
								</el-input>
							</el-form-item>
							<el-form-item>
								<el-input size="small" v-model="dataForm.sku" placeholder="物料编码" clearable></el-input>
							</el-form-item>
							<el-form-item>
								<el-input size="small" v-model="dataForm.descr" placeholder="物料名称" clearable></el-input>
							</el-form-item>
							<el-form-item>
								<el-input v-model="dataForm.factorycdoe" size="small" placeholder="计量编码/工装号" clearable>
								</el-input>
							</el-form-item>
							<el-form-item>
								<el-cascader v-model="sortvalue" :options="skucategoryList" size="small"
									placeholder="类别" :props="{ value: 'categorykey' ,label:'name',expandTrigger:'hover',checkStrictly:true }"
									:show-all-levels="false" @change="handleChange"  clearable>
								</el-cascader>
							</el-form-item>
							<el-form-item>
								<el-select size="small" v-model="dataForm.recipienttype" placeholder="类型">
									<el-option value="" label="--"> </el-option>
									<el-option v-for="item in recipientType" :key="item.list" :label="item.listname"
										:value="item.list">
									</el-option>
								</el-select>
							</el-form-item>
							<el-form-item>
								<el-button size="small" @click="getDataList()">查询</el-button>
							</el-form-item>
							<!-- <el-form-item>
                            <el-button type="primary" @click="addOrUpdateHandle()">新增</el-button>
                          </el-form-item> -->
							<!--<el-form-item>
                            <el-button type="danger" @click="deleteHandle()">删除</el-button>
                          </el-form-item>
                          -->
                          <el-form-item>
                            <el-button type="info" @click="ex()">导出</el-button>
                          </el-form-item>
						</el-form>
						<el-table v-loading="dataListLoading" :data="dataList" border style="width: 100%;"
							:span-method="arraySpanMethod" :cell-style="hejiStyle">

							<el-table-column prop="recipienttime" label="月份" header-align="center" align="center">
							</el-table-column>
							<el-table-column prop="cardId" label="领用人号" header-align="center" align="center">
							</el-table-column>
							<el-table-column prop="recipient" label="领用人" header-align="center" align="center">
							</el-table-column>
							<el-table-column prop="recipientId" label="领用人卡ID" header-align="center" align="center">
							</el-table-column>

							<el-table-column prop="recipienttype" label="类型" header-align="center" align="center">
							</el-table-column>

							<el-table-column prop="sku" label="物料编码" header-align="center" align="center">
							</el-table-column>
							<el-table-column prop="descr" label="物料名称" header-align="center" align="center">
							</el-table-column>

							<el-table-column prop="factorycdoe" label="计量编码/工装号" header-align="center" align="center">
							</el-table-column>
							<el-table-column prop="lot9" label="新旧" header-align="center" align="center">
							</el-table-column>
							<el-table-column prop="price" label="价格" header-align="center" align="center">
							</el-table-column>
							  <el-table-column prop="qty" label="数量" header-align="center" align="center">
							</el-table-column>
							<el-table-column prop="backqty" label="归还量" header-align="center" align="center">
							</el-table-column>
							<el-table-column prop="damegeqty" label="报废量" header-align="center" align="center">
							</el-table-column>
						</el-table>
					</div>
				</el-card>
			</div>
		</div>
	</div>

</template>

<script>
	import DataList from "@/utils/DataList";
	import {
		ref,
		reactive,
		onMounted,
		nextTick
	} from 'vue';
	import {
		RecipientReport
	} from "@/network/lswms/statistics/statistics.js"
    import {
        request
    } from "@/network/request";
	import {
		getCodeListByCode
	} from "@/network/lswms/base/Codelist.js"
	import {
			getSkucategoryById,
			getSkucategoryByType
		} from "@/network/lswms/base/Skucategory"
	import {
		hasPermission
	} from "@/utils/hasPermission"
	import {
		ElMessage,
		ElMessageBox
	} from 'element-plus'
	export default {
		name: "RecipientReport",
		setup() {
			const {
				mixinViewModuleOptions,
				total,
				page,
				limit,
				dataListSelectionChangeHandle,
				dataListSortChangeHandle,
				pageSizeChangeHandle,
				pageCurrentChangeHandle,
				addOrUpdateHandle,
				deleteHandle,
				exportHandle,
				addOrUpdateVisible,
				dataListSelections,
				addOrUpdate
			} = DataList();
			const dataListLoading = ref(false);
			const dataForm = ref({}) // 查询条件
			const dataList = ref([]); // 数据列表


			onMounted(() => {
				// mixinViewModuleOptions.value.getDataListIsPage = true;
				// mixinViewModuleOptions.value.getDataListURL = '/lswms/statistics/getEarlyWarning';
				// mixinViewModuleOptions.value.deleteURL = '/lswms/recipients';
				mixinViewModuleOptions.value.exportURL = '/lswms/recipients/export';
				// mixinViewModuleOptions.value.deleteIsBatchKey = 'id';
				// mixinViewModuleOptions.value.deleteIsBatch = true
				dataListLoading.value = false;
			//	getDataList();
				recipientTypeFn();
				getSkucategoryList()

			})
			const getDataList = () => {
				dataListLoading.value = true;
				RecipientReport(dataForm.value).then((res) => {
					if (res.code != 0) {
						dataList.value = [];
						return ElMessage.error(res.msg);
					}
					// dataList.value = res.data.sort(compare);

					let tableData = res.data.sort(compare);
					//显示的数据
					let showdata = [];
					// 合计 
					let heji = {
						recipienttime: '合计金额',
						cardId: '',
						recipient: '',
						price: 0,
						qty: 0,
						backqty: 0,
						damegeqty: 0
					}
					//最新统计过的记录
					let lasttongji = {};
					tableData.forEach((item, index) => {

						//第一行
						if (index == 0) {
							lasttongji = item;
							// heji.recipienttime = lasttongji.recipienttime;
							// heji.cardId = lasttongji.cardId;
							//item.price = (item.lot9="新")?lasttongji.price:0;
							heji.price += lasttongji.qty * ( (lasttongji.lot9=="新") ? lasttongji.price : 0 );
							heji.qty += (item.lot9=="新")?lasttongji.qty:0;
							heji.backqty += (item.lot9=="新")?lasttongji.backqty:0;
							heji.damegeqty += (item.lot9=="新")?lasttongji.damegeqty:0;
							showdata.push(item);
						} else
							//中间行
							if (lasttongji.recipienttime == item.recipienttime && lasttongji.cardId ==
								item.cardId) {
								//当前行 与 lasttongji 是相同组
                                //item.price = (item.lot9=="新")?lasttongji.price:0;
								heji.price += item.qty * ((item.lot9=="新")?item.price:0);
								heji.qty += (item.lot9=="新")?item.qty:0 ;
								heji.backqty += (item.lot9=="新")?item.backqty:0;
								heji.damegeqty += (item.lot9=="新")?item.damegeqty:0 ;
								showdata.push(item);
							} else {
								//当前行 与 lasttongji 不是相同组
								showdata.push(heji);

								heji = {
									recipienttime: '合计金额',
									cardId: '',
									recipient: '',
                                    price: 0,
									qty: 0,
									backqty: 0,
									damegeqty: 0
								};

								lasttongji = item;
								// heji.recipienttime = lasttongji.recipienttime;
								// heji.cardId = lasttongji.cardId;
                                //item.price = (item.lot9=="新")?lasttongji.price:0;
                                heji.price += lasttongji.qty * ((lasttongji.lot9=="新")?lasttongji.price:0);
								heji.qty += (lasttongji.lot9=="新")?lasttongji.qty:0;
								heji.backqty += (lasttongji.lot9=="新")?lasttongji.backqty:0 ;
								heji.damegeqty += (lasttongji.lot9=="新")?lasttongji.damegeqty:0 ;
								showdata.push(item);
							}

						//最后一行
						if (index == tableData.length - 1) {
							showdata.push(heji);
						}

					})


					dataList.value = showdata;

					dataListLoading.value = false;
				})

			}

			const ex=()=>{
			    //dataForm.value = dataList.value
				exportHandle1().then(()=>{
				    alert(dataForm.value);
				})
			}

			const arraySpanMethod = ({
				row,
				column,
				rowIndex,
				columnIndex
			}) => {
				if (row.recipienttime == '合计金额') {
					if (columnIndex == 0) {
						return [1, 9]
					} else if (columnIndex >= 1 && columnIndex < 9) {
						return [0, 0]
					}

				}
			}

			const hejiStyle = ({
				row,
				column,
				rowIndex,
				columnIndex
			}) => {
				if (row.recipienttime == '合计金额') {
					return " background:#82b2ff"
				}
			}

			const compare = function(obj1, obj2) {
				var recipienttime1 = obj1.recipienttime;
				var recipienttime2 = obj2.recipienttime;
				if (recipienttime1 < recipienttime2) {
					return -1;
				} else if (recipienttime1 > recipienttime2) {
					return 1;
				} else {
					var cardId1 = obj1.cardId;
					var cardId2 = obj2.cardId;
					if (cardId1 < cardId2) {
						return -1;
					} else if (cardId1 > cardId2) {
						return 1;
					} else {
						var recipienttype1 = obj1.recipienttype;
						var recipienttype2 = obj2.recipienttype;
						if (recipienttype1 < recipienttype2) {
							return -1;
						} else if (recipienttype1 > recipienttype2) {
							return 1;
						} else {
							return 0;
						}
						return 0;
					}
					return 0;
				}
			}

			//领用类型
			const recipientType = ref("");
			const recipientTypeFn = () => {
				getCodeListByCode('RECIPIENTTYPE').then((res) => {
					if (res.code != 0) {
						return ElMessage.error(res.msg);
					}
					recipientType.value = res.data;
				}).catch((err) => {});
			}
			
			
			const sortvalue = ref([]);
			const handleChange = (sortvalue) =>{
				dataForm.value.sort = "";
				if(!sortvalue){
					return ;
				}
				for (let i = 0; i < sortvalue.length; i++) {
					dataForm.value.sort += sortvalue[i] + '#';
				}
				// console.log(dataForm.value.sort );
			}
			const skucategoryList = ref([]);
			const getSkucategoryList = () => {
				return getSkucategoryByType(0)
					.then(function(res) {
						if (res.code !== 0) {
							return ElMessage.error(res.msg);
						}
						// skucategoryList.value = res.data;
			
						let data1 = [];
						createList(res.data, data1);
						skucategoryList.value = data1;
					})
					.catch(function() {});
			}
			const createList = (sourcedata, targetdata) => {
				for (let i = 0; i < sourcedata.length; i++) {
					let tempdata = sourcedata[i];
					if (tempdata.children.length > 0) {
						let children = {
							categorykey: '',
							name: '',
							children: []
						}
						children.categorykey = tempdata.categorykey;
						children.name = tempdata.name;
						createList(tempdata.children, children.children);
						targetdata.push(children)
					} else {
						let children = {
							categorykey: '',
							name: ''
						}
						children.categorykey = tempdata.categorykey;
						children.name = tempdata.name;
						targetdata.push(children)
					}
				}
			
			}
            const exportHandle1 = () => {
                request({
                    url: '/lswms/recipients/export2',
                    method: 'get',
                    params: dataForm.value,
                    responseType: 'blob'
                }).then((res) => {
                    let fileName = 'SamplePointsDetail.xls' //excel文件名称
                    let blob = new Blob([res.data], {
                        type: 'application/x-xls'
                    }) //word文档为msword,pdf文档为pdf，excel文档为x-xls
                    if (window.navigator.msSaveOrOpenBlob) {
                        navigator.msSaveBlob(blob, fileName);
                    } else {
                        var link = document.createElement('a');
                        link.href = window.URL.createObjectURL(blob);
                        link.download = fileName;
                        link.click();
                        window.URL.revokeObjectURL(link.href);
                    }
                })
            }

			return {
				dataForm,
				// mixinViewModuleOptions,
				getDataList,
				dataList,
				dataListLoading,
				arraySpanMethod,
				hejiStyle,
				recipientTypeFn,
				recipientType,
				skucategoryList,
				sortvalue,
				handleChange,
				// total,
				// page,
				// limit,
				// dataListLoading,
				// dataListSelectionChangeHandle,
				// dataListSortChangeHandle,
				// pageSizeChangeHandle,
				// pageCurrentChangeHandle,
				// addOrUpdateHandle,
				// deleteHandle,
				exportHandle,
				// addOrUpdateVisible,
				// dataListSelections,
				// addOrUpdate
                exportHandle1,
				ex,
			}
		},
		methods: {
			hasPermission
		}
	}
</script>

<style scoped>

</style>
